<script setup lang="ts">
import {computed, PropType, ref} from "vue";
import {useContextMenu} from "./useContextMenu.js";
import {useViewPort} from "./useViewPort.js";
import {ContextMenuItemType, ContextMenusType} from "@/components/ContextMenu/types.ts";

const $emit = defineEmits(['select'])
defineProps({
  menus: {
    type: Array as PropType<ContextMenusType>,
    default: () => []
  },
  style: {
    default: {}
  }
})
defineOptions({
  name: "ContextMenu"
})

const containerRef = ref(null)
const {x, y, showMenu} = useContextMenu(containerRef)

const handleClick = (item: ContextMenuItemType) => {
  showMenu.value = false
  $emit('select', item)
}

const w = ref(0)
const h = ref(0)

const handleSize = ({width, height}) => {
  console.log("handleSize", width, height)
  w.value = width
  h.value = height
}
const [vw, vh] = useViewPort()
// 视口尺寸
const pos = computed(() => {
  // 需要知道鼠标位置、视口尺寸、菜单尺寸
  let posX = x.value
  let posY = y.value
  // if(x.value > vw.value - w.value){
  //   posX -= w.value
  // }
  // if(y.value > vh.value - h.value){
  //   posY -= y.value - vh.value + h.value
  // }
  return {
    posX,
    posY
  }
})


</script>

<template>
  <div ref="containerRef">
    <slot></slot>
    <Teleport to="body">
        <div class="context-menu"
             :class="{animation: showMenu}"
             :style="{
                left: pos.posX + 'px',
                top: pos.posY + 'px',
                ...style
             }">
          <ul v-size-ob="handleSize"
              class="menu-list">
            <li class="menu-item"
                @click="handleClick(item)"
                v-for="(item, index) in menus" :key="index">{{ item.title }}
            </li>
          </ul>
        </div>
    </Teleport>
  </div>
</template>

<style scoped>

.context-menu {
  position: fixed;
  background: #0D1016;
  box-shadow: rgba(0, 0, 0, 0.5) 0 10px 30px;
  min-width: 120px;
  border-radius: 8px;
  font-size: 12px;
  color: white;
  line-height: 1.8;
  white-space: nowrap;
  overflow: hidden;
  z-index: 999;

  display: none;
  &.animation {
    display: block;
    transform-origin: 0 0;
    animation: 0.2s ease 0s 1 normal both running scale;
  }
}
@keyframes scale {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  60% {
    transform: scale(1.03);
    opacity: 1;
  }
  100% {
    transform: scale(1);
  }
}


.menu-list {
  padding: 6px;
  margin: 0;
  cursor: pointer;
  border-radius: 4px;
  user-select: none;
}

.menu-item {
  padding: 2px 6px;
  margin: 0;
  cursor: pointer;
  border-radius: 4px;
  user-select: none;
}


.menu-item:hover {
  background: #272A2F;
  color: #fff;
}

</style>
